package com.sakura.二分查找;

public class Code33_搜索旋转排序数组 {


    public int search1(int[] nums, int target) {
        int n = nums.length;
        int minI = finMin(nums);
        if (target > nums[n - 1]) {
            return lowerBound(nums, -1, minI, target);
        }

        return lowerBound(nums, minI - 1, n, target);
    }

    public int finMin(int[] nums) {
        int n = nums.length;
        int left = -1;
        int right =n - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < nums[n - 1]) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return right;


    }

    public int lowerBound(int[] nums, int left , int right, int target) {
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return nums[right] == target ? right : -1;
    }

    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            if (nums[left] <= nums[mid]) {
                if (target < nums[mid] && target >= nums[left]) {
                    left = mid + 1;
                } else {
                    right = mid -1;
                }
            } else {
                if (target > nums[mid] && target < nums[right]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
        }
        return -1;
    }
}
